package top.lyc829.myvideoplayer.ui.play;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.BounceInterpolator;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.model.VideoOptionModel;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.yhao.floatwindow.FloatWindow;
import com.yhao.floatwindow.MoveType;
import com.yhao.floatwindow.Screen;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import top.lyc829.myvideoplayer.R;
import top.lyc829.myvideoplayer.tool.FloatUtil;
import top.lyc829.myvideoplayer.ui.view.FloatPlayerView;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class PlayActivity extends AppCompatActivity {

    StandardGSYVideoPlayer videoPlayer;

    OrientationUtils orientationUtils;

    String filePath, fileName;
    TextView videoSpeedTextView, startWindow;
    float videoSpeed = 1f;

    SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        Objects.requireNonNull(getSupportActionBar()).hide();
        setContentView(R.layout.activity_play);

        filePath = this.getIntent().getStringExtra("filePath");
        fileName = filePath.substring(filePath.lastIndexOf("/") + 1);

        long lastPlayPosition = getLastPosition();
        if (lastPlayPosition > 0) {     // 跳转到某个精确时间播放
            VideoOptionModel videoOptionModel =
                    new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "seek-at-start", (int)lastPlayPosition);
            List<VideoOptionModel> list = new ArrayList<>();
            list.add(videoOptionModel);
            GSYVideoManager.instance().setOptionModelList(list);
        }

        init();

        // 小窗播放
        startWindow = findViewById(R.id.startWindow);
        startWindow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= 23) {
                    if (!FloatUtil.hasPermission(v.getContext())) {
                        requestAlertWindowPermission();
                    }
                }
                if (FloatWindow.get() == null) {
                    FloatPlayerView floatPlayerView = new FloatPlayerView(getApplicationContext(), filePath);

                    //EasyFloat.with(v.getContext()).setLayout(R.layout.activity_play).show();

                    FloatWindow
                            .with(getApplicationContext())
                            .setView(floatPlayerView)
                            .setWidth(Screen.width, 0.4f)
                            .setHeight(Screen.width, 0.3f)
                            .setX(Screen.width, 0.8f)
                            .setY(Screen.height, 0.3f)
                            .setMoveType(MoveType.slide)
                            .setDesktopShow(true)
                            .setFilter(false)
                            .setMoveStyle(500, new BounceInterpolator())
                            .build();
                    FloatWindow.get().show();
                }

            }
        });

        videoSpeedTextView = findViewById(R.id.video_speed);
        videoSpeedTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoSpeed == 1f) {
                    videoSpeed = 1.5f;
                } else if (videoSpeed == 1.5f) {
                    videoSpeed = 2f;
                } else if (videoSpeed == 2f) {
                    videoSpeed = 0.5f;
                } else if (videoSpeed == 0.5f) {
                    videoSpeed = 1f;
                } else {
                    videoSpeed = 1f;
                }
                videoSpeedTextView.setText(String.valueOf(videoSpeed)  + "倍速");
                videoPlayer.setSpeedPlaying(videoSpeed, true);

            }
        });


    }

    // 获取上次播放时间
    private long getLastPosition() {
        sp = getSharedPreferences("cache", Context.MODE_PRIVATE);
        return sp.getLong(filePath, 0);
    }


    @RequiresApi(api = 23)
    private void requestAlertWindowPermission() {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, 1);
    }

    @RequiresApi(api = 23)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Build.VERSION.SDK_INT >= 23){
            //todo 用23以上编译即可出现canDrawOverlays
            if (FloatUtil.hasPermission(this)) {

            } else {
                this.finish();
            }
        }
    }





    private void init() {

        videoPlayer =  (StandardGSYVideoPlayer)findViewById(R.id.video_player);


        //String source1 = "http://9890.vod.myqcloud.com/9890_4e292f9a3dd011e6b4078980237cc3d3.f20.mp4";
        videoPlayer.setUp(filePath, true, fileName);

        //增加title
        videoPlayer.getTitleTextView().setVisibility(View.VISIBLE);
        //设置返回键
        videoPlayer.getBackButton().setVisibility(View.VISIBLE);
        //设置旋转
        orientationUtils = new OrientationUtils(this, videoPlayer);
        //设置全屏按键功能,这是使用的是选择屏幕，而不是全屏
        videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                orientationUtils.resolveByClick();
            }
        });
        //是否可以滑动调整
        videoPlayer.setIsTouchWiget(true);
        //设置返回按键功能
        videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        videoPlayer.startPlayLogic();


    }


    @Override
    protected void onPause() {
        super.onPause();
        videoPlayer.onVideoPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoPlayer.onVideoResume();
    }

    @Override
    protected void onDestroy() {

        // 获取此时观看的位置
        long playPosition = GSYVideoManager.instance().getCurrentPosition();
        // 保存此时观看的时间
        SharedPreferences.Editor editor = sp.edit();
        editor.putLong(filePath, playPosition);
        editor.apply();

        //清除全局设置，即从精确位置播放的设置
        GSYVideoManager.instance().setOptionModelList(null);

        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
        if (orientationUtils != null)
            orientationUtils.releaseListener();
        /**
         * 这里在返回主页的时候销毁了，因为不想和DEMO中其他页面冲突
         */
        FloatWindow.destroy();
    }

}